package com.example.book.web;

import com.example.book.pojo.User;
import com.example.book.service.UserService;
import com.example.book.service.impl.UserServiceImpl;
import com.example.book.utils.WebUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;
//@WebServlet(name = "registServlet", value = "/registServlet")
public class RegistServlet extends HttpServlet {
    UserService userService = new UserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取请求的参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String code = request.getParameter("code");



        //2.检查 验证码是否正确 ===>写死 abcd

        if ("abcd".equalsIgnoreCase(code)){
            //正确
            //3.检查 用户名是否可用
            if (userService.existsUsername(username)){
                //不可用
                request.setAttribute("username",username);
                request.setAttribute("email",email);
                request.setAttribute("msg","用户名["+username+"]已存在");
                System.out.println("用户名["+username+"]已存在");
                //跳回注册页面
                request.getRequestDispatcher("/pages/user/regist.jsp").forward(request,response);
            }else {
                //可用
                //调用service保存到数据库
                userService.regisUser(new User(null,username,password,email));
                //跳转到注册成功页面
                request.getRequestDispatcher("/pages/user/regist_success.jsp").forward(request,response);
            }


        }else {
            //不正确
            //跳回注册页面
            request.setAttribute("username",username);
            request.setAttribute("email",email);
            request.setAttribute("msg","验证码["+code+"]错误");
            System.out.println("验证码["+code+"]错误");
            request.getRequestDispatcher("/pages/user/regist.jsp").forward(request,response);
        }


    }
}
